import React, { useEffect, useState } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  ActivityIndicator,
  StatusBar 
} from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { FontAwesome } from '@expo/vector-icons';
import { auth } from './utils/auth';
import LoginScreen from './components/LoginScreen';
import ChatScreen from './components/ChatScreen';
import ProductListScreen from './components/ProductListScreen';

const Stack = createStackNavigator();

export default function App() {
  const [isLoading, setIsLoading] = useState(true);
  const [initialRoute, setInitialRoute] = useState('LoginScreen');

  // 初始化应用，检查用户登录状态
  useEffect(() => {
    const initializeApp = async () => {
      try {
        // 检查用户是否已登录
        const isLoggedIn = await auth.isLoggedIn();
        
        // 如果已登录，验证token是否有效
        if (isLoggedIn) {
          const isValidToken = await auth.validateToken();
          setInitialRoute(isValidToken ? 'ProductListScreen' : 'LoginScreen');
        } else {
          setInitialRoute('LoginScreen');
        }
      } catch (error) {
        console.error('初始化应用失败:', error);
        setInitialRoute('LoginScreen');
      } finally {
        setIsLoading(false);
      }
    };

    initializeApp();
  }, []);

  // 显示加载屏幕
  if (isLoading) {
    return (
      <SafeAreaProvider>
        <View style={styles.loadingContainer}>
          <View style={styles.logoContainer}>
            <FontAwesome name="shopping-bag" size={50} color="#007AFF" />
          </View>
          <Text style={styles.loadingText}>电商智能客服系统</Text>
          <ActivityIndicator size="large" color="#007AFF" style={styles.loadingIndicator} />
        </View>
      </SafeAreaProvider>
    );
  }

  return (
    <SafeAreaProvider>
      <StatusBar barStyle="dark-content" backgroundColor="#f5f5f5" />
      <NavigationContainer>
        <Stack.Navigator 
          initialRouteName={initialRoute}
          screenOptions={{
            headerShown: false,
          }}
        >
          <Stack.Screen name="LoginScreen" component={LoginScreen} />
          <Stack.Screen name="ChatScreen" component={ChatScreen} />
          <Stack.Screen name="ProductListScreen" component={ProductListScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    </SafeAreaProvider>
  );
}

const styles = StyleSheet.create({
  loadingContainer: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    justifyContent: 'center',
    alignItems: 'center',
  },
  logoContainer: {
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: '#e8f4f8',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 24,
  },
  loadingText: {
    fontSize: 20,
    fontWeight: '600',
    color: '#333',
    marginBottom: 24,
  },
  loadingIndicator: {
    marginTop: 16,
  },
});